<?php
namespace cms\modules\backend\controllers;

use Yii;
use yii\db\Expression;
use cms\controllers\AuthController;
use app\models\DynamicData;
use app\models\DynamicDataFlag;
use app\models\DynamicDataAttr;
use app\models\DynamicDataInfo;
use app\models\DynamicDataList;
use common\component\exception\ErrMap;
use common\component\tool\Tool;
use common\models\OperationLog;
use common\behaviors\Sort;


class DynamicDataController extends AuthController
{
    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

    /*动态数据列表*/
    public function actionDynamicDataList()
    {
        if(isset($this->get['page'])){
            $currPage = intval($this->get['page']?$this->get['page']:1);
        }else{
            $currPage = 1;
        }
        $pageSize = Tool::getPageSize();

        $dynamicData = new DynamicData;
        $count = $dynamicData::find()->where('app_id = :app_id', [':app_id' => $this->app_id])->count();
        $dynamicDataList = $dynamicData::find()
                        ->where('app_id = :app_id', [':app_id' => $this->app_id])
                        ->orderBy([
                            'sort' => SORT_DESC,
                            'add_time' => SORT_DESC
                        ])
                        ->offset($pageSize*($currPage-1))->limit($pageSize)
                        ->asArray()->all();
        $res = array(
            'list' => $dynamicDataList,
            'pageInfo' => array(
                'count' => intval($count),
                'currPage' => $currPage,
                'pageSize' => $pageSize,
            ),
        );
        return Tool::showRes([0, '获取成功'], $res);
    }

    /*添加动态数据*/
    public function actionAddDynamicData()
    {
        if(Yii::$app->request->isPost){
            // P($this->post);
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*1、添加动态数据*/
                $dynamicData = new DynamicData;
                if(($id = $dynamicData->addDynamicData($this->post, $this->app_id)) === false){
                    $pass = false;
                    if($dynamicData->hasErrors()){
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $dynamicData->getErrors();//异常信息
                    }
                }
                // P($id);

                /*2、添加动态数据标签*/
                // P($this->post['DynamicDataFlag']['flagname']);
                if($pass and isset($this->post['DynamicDataFlag']['flagname']) and
                    !empty($this->post['DynamicDataFlag']['flagname'])){
                    $dynamicDataFlag = new DynamicDataFlag;
                    if(!$dynamicDataFlag->addDynamicDataFlag($this->post, $id)){
                        $pass = false;
                        if($dynamicDataFlag->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $dynamicDataFlag->getErrors();//异常信息
                        }
                    }

                    /*更新默认标示，因为需要先添加动态数据，才有动态ID, 再插入标示数据，最后更新默认标示组合*/
                    $defaultflagnum = 0;//默认的标示数字
                    /*如果有默认的标示，需要整理成组合数字再入库*/
                    if(isset($this->post['DynamicData']['defaultflagnum']) and
                        is_array($this->post['DynamicData']['defaultflagnum']) and
                        count($this->post['DynamicData']['defaultflagnum']) > 0){
                        // P($this->post['DynamicData']['defaultflagnum']);
                        foreach($this->post['DynamicData']['defaultflagnum'] as $k => $v){
                            $defaultflagnum += Yii::$app->params['dynamicRule']['origin'][$v];
                        }
                        DynamicData::updateAll(['defaultflagnum' => $defaultflagnum], 'dynamic_id = ' . $id);
                    }
                }




                if($pass){
                    $backInfo = [0, '添加APP动态数据成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };

        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }


    /*修改动态数据*/
    public function actionModifyDynamicData()
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            // P($this->get);
            $id = isset($this->get['id'])?$this->get['id']:'';
            if($id){
                $dynamicData = DynamicData::find()
                            ->where('{{%dynamic_data}}.dynamic_id = :id', [':id' => $id])
                            ->joinWith('flag')
                            ->asArray()->one();
                // P($dynamicData);
                if(!is_null($dynamicData)){
                    if($dynamicData['defaultflagnum'] > 0){
                        $dynamicData['defaultflagnum'] = Yii::$app->params['dynamicRule']['groupToOrigin'][$dynamicData['defaultflagnum']-1];
                        foreach($dynamicData['defaultflagnum'] as $k => $v){
                            $dynamicData['defaultflagnum'][$k] = array_search($v, Yii::$app->params['dynamicRule']['origin']);
                        }
                    }else{
                        $dynamicData['defaultflagnum'] = '';
                    }
                    // P($dynamicData);
                    return Tool::showRes([0, '获取成功'], $dynamicData);
                };
            }
        }


        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $id = isset($this->post['DynamicData']['id'])?intval($this->post['DynamicData']['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*1、先删除，再添加动态数据标签*/
                    // P($this->post['DynamicDataFlag']['flagname']);
                    DynamicDataFlag::deleteAll('dynamic_id = :id', [':id' => $this->post['DynamicData']['id']]);
                    if($pass and isset($this->post['DynamicDataFlag']['flagname']) and
                        !empty($this->post['DynamicDataFlag']['flagname'])){
                        $max = count(Yii::$app->params['dynamicRule']['origin']);
                        if(count(explode("\n", $this->post['DynamicDataFlag']['flagname'])) > $max){
                            $pass = false;
                            $backInfo = ErrMap::getError(10005, '数据标示不能超过'. $max .'个');
                        }
                        $dynamicDataFlag = new DynamicDataFlag;
                        if(!$dynamicDataFlag->addDynamicDataFlag($this->post, $this->post['DynamicData']['id'])){
                            $pass = false;
                            if($dynamicDataFlag->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $dynamicDataFlag->getErrors();//异常信息
                            }
                        }

                        /*如果有默认的标示，需要整理成组合数字再入库*/
                        $defaultflagnum = 0;//默认的标示数字，防止报错
                        if(isset($this->post['DynamicData']['defaultflagnum']) and
                            is_array($this->post['DynamicData']['defaultflagnum']) and
                            count($this->post['DynamicData']['defaultflagnum']) > 0){
                            // P($this->post['DynamicData']['defaultflagnum']);
                            foreach($this->post['DynamicData']['defaultflagnum'] as $k => $v){
                                $defaultflagnum += Yii::$app->params['dynamicRule']['origin'][$v];
                            }
                            // P($this->post);
                        }
                        $this->post['DynamicData']['defaultflagnum'] = $defaultflagnum;
                    }

                    /*２、修改动态数据*/
                    $dynamicData = new DynamicData;
                    if(!$dynamicData->modifyDynamicData($this->post, $id)){
                        $pass = false;
                        if($dynamicData->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $dynamicData->getErrors();//异常信息
                        }
                    }

                    if($pass){
                        $backInfo = [0, '修改动态数据成功'];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();
                };
            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*删除动态数据*/
    public function actionDeleteDynamicData()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        if($id){
            /*查看此栏目下，是否有数据，如果有，将不能删除*/
            $dynamicDataInfo = new DynamicDataInfo;
            $res = $dynamicDataInfo::find()
                        ->where('app_id = :app_id and dynamic_id = :id', [':app_id' => $this->app_id, ':id' => $this->get['id']])
                        ->one();
            if(is_null($res)){
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    /*删除su_cms_dynamic_data表数据*/
                    $dynamicData = new DynamicData;
                    if($dynamicData->deleteAll('dynamic_id = :id', [':id' => $id]) < 0){
                        $pass = false;
                        $backInfo = ErrMap::getError(10013, '删除动态数据失败');//返回信息
                    }

                    /*删除su_cms_dynamic_data_attr表数据*/
                    $dynamicDataAttr = new DynamicDataAttr;
                    if($dynamicDataAttr->deleteAll('dynamic_id = :id', [':id' => $id]) < 0){
                        $pass = false;
                        $backInfo = ErrMap::getError(10013, '删除动态数据失败');//返回信息
                    }

                    /*删除su_cms_dynamic_data_flag表数据*/
                    $dynamicDataFlag = new DynamicDataFlag;
                    if($dynamicDataFlag->deleteAll('dynamic_id = :id', [':id' => $id]) < 0){
                        $pass = false;
                        $backInfo = ErrMap::getError(10013, '删除动态数据标示失败');//返回信息
                    }


                    if($pass){
                        $backInfo = [0, '删除动态数据成功'];//返回信息
                        $transaction->commit();
                    }

                }catch(\Exception $exception){
                    throw new \Exception ($exception->getMessage());
                    $transaction->rollback();
                };

            }else{
                $backInfo = [10013, '含有动态数据，不能删除'];//返回信息
            }

            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), '') ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*排序*/
    public function actionSetSort()
    {
        if(Yii::$app->request->isPost){
            $sort = $this->post['sort'];
            // P($sort);
            if(!empty($sort) and is_array($sort)){
                if($this->setSortList(new DynamicData, $sort)){
                    $backInfo = [0, '设置动态数据排序成功'];//返回信息
                }

            }
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*下面是动态数据内容操作，操作的另一张表==========================*/
    /*动态数据内容列表*/
    public function actionDynamicDataInfoList()
    {
        if(isset($this->get['id']) and is_numeric($this->get['id'])){
            if(isset($this->get['page'])){
                $currPage = intval($this->get['page']?$this->get['page']:1);
            }else{
                $currPage = 1;
            }
            $pageSize = Tool::getPageSize();

            $dynamicDataInfo = new DynamicDataInfo;
            $count = $dynamicDataInfo::find()
                            ->where('app_id = :app_id and dynamic_id = :id', [':app_id' => $this->app_id, ':id' => $this->get['id']])
                            ->count();
            $dynamicDataInfoList = $dynamicDataInfo::find()
                            ->select(['info_id', 'dynamic_id', 'flagnum', 'ip', 'sessionid', 'client', 'praise_num', 'reply_num', 'state', 'add_time'])
                            ->where('app_id = :app_id and dynamic_id = :id', [':app_id' => $this->app_id, ':id' => $this->get['id']])
                            ->with('content')
                            ->with('attrName')
                            ->with('flag')
                            ->orderBy([
                                'add_time' => SORT_DESC
                            ])
                            ->offset($pageSize*($currPage-1))->limit($pageSize)
                            ->asArray()->all();
            foreach($dynamicDataInfoList as $k => $v){
                $dynamicDataInfoList[$k]['ip'] = $v['ip'];

                if($v['flag']){
                    $dynamicDataInfoList[$k]['flag']['flagname'] = explode("\n", $v['flag']['flagname']);
                }

                if($v['flagnum']){
                    // echo $v['flagnum'];
                    $dynamicDataInfoList[$k]['flagnum'] = Yii::$app->params['dynamicRule']['groupToOrigin'][$v['flagnum']-1];
                    foreach($dynamicDataInfoList[$k]['flagnum'] as $k1 => $v1){
                        $dynamicDataInfoList[$k]['flagnum'][$k1] = array_search($v1, Yii::$app->params['dynamicRule']['origin']);
                    }
                    // echo Yii::$app->params['dynamicRule']['origin']
                }else{
                    $dynamicDataInfoList[$k]['flagnum'] = '';
                }

                // foreach($v['content'] as $k1 => $v1){
                //     $dynamicDataInfoList[$k][$v1['attr_enname']] = $v1['attr_value'];
                // }
                // unset($dynamicDataInfoList[$k]['content']);
            }
            // P($dynamicDataInfoList);
            $res = array(
                'list' => $dynamicDataInfoList,
                'pageInfo' => array(
                    'count' => intval($count),
                    'currPage' => $currPage,
                    'pageSize' => $pageSize,
                ),
            );
            return Tool::showRes([0, '获取成功'], $res);
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*处理数据，更改标示，包括回复数据（还未实现）*/
    public function actionDealContent()
    {
        // P($this->post);
        if(Yii::$app->request->isPost){

            $id = isset($this->post['flagData']['id'])?$this->post['flagData']['id']:'';
            // P($this->post['flagData']);
            $flagnum = 0;
            if(isset($this->post['flagData']['flagIndex'])){
                foreach($this->post['flagData']['flagIndex'] as $k => $v){
                    // P(Yii::$app->params['dynamicRule']['origin'][$v], false);
                    $flagnum += Yii::$app->params['dynamicRule']['origin'][$v];
                }
            }
            // echo $flagnum;

            if($id){
                $dynamicDataInfo = new DynamicDataInfo;
                if($dynamicDataInfo->updateAll(['flagnum' => $flagnum], 'app_id = :app_id and info_id = :id', [':app_id' => $this->app_id, ':id' => $id]) >= 0){//成功
                    $backInfo = [0, '更新标示状态成功'];//返回信息
                }
                
                if(!isset($backInfo)){
                    $backInfo = ErrMap::getError(10005);//返回信息
                }
                if(!isset($exception)){
                    $exception = '';//异常信息
                }
                //操作日志
                if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                    return $res;
                };
            }
        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*更改前台显示状态*/
    public function actionChangeContentState()
    {
        $id = isset($this->post['id'])?$this->post['id']:'';
        $state = (isset($this->post['state']) and $this->post['state'] == 'true')?2:1;
        // P($this->app_id);
        if($id){
            $dynamicDataInfo = new DynamicDataInfo;
            if($res = $dynamicDataInfo->updateAll(['state' => $state], 'app_id = :app_id and info_id = :id', [':app_id' => $this->app_id, ':id' => $id])){//成功
                $backInfo = [0, '更改动态数据内容状态成功'];//返回信息
            }
            
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }


    /*删除动态数据内容*/
    public function actionDeleteDynamicContent()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        if($id){
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                /*删除su_cms_dynamic_data_info中的数据*/
                $dynamicDataInfo = new DynamicDataInfo;
                if(!$dynamicDataInfo->deleteAll('info_id = :id', [':id' => $id])){
                    $pass = false;
                    $backInfo = ErrMap::getError(10013, '删除动态数据内容失败');//返回信息
                }

                /*删除su_cms_dynamic_data_list表中的数据*/
                $dynamicDataList = new DynamicDataList;
                if(!$dynamicDataList->deleteAll('info_id = :id', [':id' => $id])){
                    $pass = false;
                    $backInfo = ErrMap::getError(10013, '删除动态数据内容列表失败');//返回信息
                }

                if($pass){
                    $backInfo = [0, '删除动态数据内容成功'];//返回信息
                    $transaction->commit();
                }

            }catch(\Exception $exception){
                $transaction->rollback();
            };
            
            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog(Tool::operationLogArgs($backInfo, $this->userInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }
        return Tool::showRes(ErrMap::getError(10005));
    }




}
